package com.guangzhi.weijianzhi.company.manager;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.pay.demo.PayAllUtuils;
import com.guangzhi.weijianzhi.R;
import com.guangzhi.weijianzhi.activity.BaseActivity;
import com.guangzhi.weijianzhi.adapter.DialogAdapter;
import com.guangzhi.weijianzhi.company.manager.PublishPositionThreeActivity.CloseReceiver;
import com.guangzhi.weijianzhi.entity.PublishPositionEntity;
import com.guangzhi.weijianzhi.http.HttpRequestUtils;
import com.guangzhi.weijianzhi.http.MyAsyncHttpResponseHandler;
import com.guangzhi.weijianzhi.mainhome.PositionListFindActivity;
import com.guangzhi.weijianzhi.utils.Misc;
import com.guangzhi.weijianzhi.utils.PopuUtils;
import com.jungly.gridpasswordview.GridPasswordView;
/**
 * 支付界面
 * @author ht
 *
 */
public class PaySelectActivity extends BaseActivity implements OnCheckedChangeListener, OnClickListener {

	private TextView noney,noney2,mPrice,mTime,mSetvice,mDay;
	private LinearLayout mLin;
	private LinearLayout mLinPop;
	private String payType ="0";
	private TextView mPay_type;
	private String mJobID;
	private String totalAmount;
	private CloseReceiver closeReceiver;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		String date = getIntent().getStringExtra("date");
		setContentView(R.layout.tz_payselect_layout);
		initView();
		parseDate(date);
		onregistBroab();
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(closeReceiver);
	}
	
	private void onregistBroab() {
		// TODO Auto-generated method stub
		closeReceiver = new CloseReceiver();  
		IntentFilter intentFilter = new IntentFilter("com.guangzhi.weijianzhi");  
		registerReceiver(closeReceiver, intentFilter);  
	}
	   /** 
	    * 结束Activity的广播接收机 
	    * @author shuxiang 
	    * 
	    */  
	   public class CloseReceiver extends BroadcastReceiver  
	{   
	       @Override  
	       public void onReceive(Context context, Intent intent)  
	       {  
	    	   PaySelectActivity.this.finish();  
	       }  
	   } 
	private void parseDate(String date) {
		// TODO Auto-generated method stub 
		try {
			JSONObject jsonO = new JSONObject(date);
			
			JSONArray optJSONArray = jsonO.optJSONArray("data");
			if(optJSONArray.length()!=0){
				
				JSONObject optJSONObject = optJSONArray.optJSONObject(0);
				totalAmount = optJSONObject.optString("totalAmount");
				noney.setText(optJSONObject.optString("totalAmount")+"元");
				noney2.setText("￥"+optJSONObject.optString("totalAmount")+"元");
				mPrice.setText("单价:"+optJSONObject.optString("unitPrice"));
				mTime.setText("时长:"+optJSONObject.optString("workLength"));
				mSetvice.setText("增值服务:"+optJSONObject.optString("addServerType"));
				mDay.setText("服务天数:"+optJSONObject.optString("addServerLength")+"天");
				mJobID = optJSONObject.optString("jobId");
			PublishPositionEntity.hasPayPassword = optJSONObject.optBoolean("hasPayPassword");//用来判断有没有设置支付密码
			}
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initView() {
		// TODO Auto-generated method stub
		initTitle();
		titleTextV.setText("确认账单");
		goBack.setOnClickListener(this);
		noney = (TextView) findViewById(R.id.money);
		 noney2 = (TextView) findViewById(R.id.monty_two);
		  mPrice = (TextView) findViewById(R.id.price);
		  mTime = (TextView) findViewById(R.id.tiem);
		  mSetvice = (TextView) findViewById(R.id.service);
		  mDay = (TextView) findViewById(R.id.day);
		  mLin = (LinearLayout) findViewById(R.id.details_lin);
		  mLinPop = (LinearLayout) findViewById(R.id.lin_pop);
		  mPay_type = (TextView) findViewById(R.id.pay_type);
		  findViewById(R.id.pay).setOnClickListener(this);
		  mLinPop.setOnClickListener(this);
		  CheckBox check = (CheckBox) findViewById(R.id.check);
		  check.setOnCheckedChangeListener(this);
		
		
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if(isChecked){
			mLin.setVisibility(View.VISIBLE);
			
		}else{
			mLin.setVisibility(View.GONE);
		}
		
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		
		case R.id.lin_pop:
			showPopFour(mLinPop);
			break;

		case R.id.pay:
			if("1".equals(payType)){//如果是选择余额支付
				if(!PublishPositionEntity.hasPayPassword){//如果用户没有设置支付密码
					Intent intent = new Intent(this, PayPassWrodActivity.class);
					startActivity(intent);
					
				}else{
					showPayDialog();
				}
				
			}else{
				Pay("", "alipay");
			}
			break;
		}
	}
	
private void showPayDialog() {
		// TODO Auto-generated method stub
	View view = View.inflate(this, R.layout.tz_pay_dialog_layout, null);
	final GridPasswordView mPasView = (GridPasswordView) view.findViewById(R.id.pswView);
   view.findViewById(R.id.forget_password_input).setOnClickListener(this);
	new  AlertDialog.Builder(this)  
	   .setTitle("支付密码" )  
	   .setView(view)  
	   .setNegativeButton("取消" , null)  
	    .setPositiveButton("确定" ,new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if(!Misc.notNull(mPasView.getPassWord())){
					Misc.alert("请输入支付密码");
				}else if(mPasView.getPassWord().length()!=6){
					Misc.alert("支付密码只能为六位");
				}else{
					
					Pay(mPasView.getPassWord(),"bonus");
				}
			}
		} ) 
	   .show();
	}

private void showPopFour(View v){
		
		View inflate = View.inflate(this, R.layout.tz_sort_layout, null);
		
		ListView listView__order  = (ListView)inflate. findViewById(R.id.jzpsn_list_find__order);
		final ArrayList<String> arraylist_order = new ArrayList<String>();
		arraylist_order.add("支付宝支付");
		arraylist_order.add("账户余额支付");
		DialogAdapter adapter_order = new DialogAdapter(PaySelectActivity.this,arraylist_order);
		listView__order.setAdapter(adapter_order);
		
		final PopupWindow  popupWindowFour = new PopupWindow(inflate,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,true);  
	        
		   popupWindowFour.setFocusable(true);  
		   popupWindowFour.setOutsideTouchable(true);  
		   popupWindowFour.setBackgroundDrawable(new BitmapDrawable()); 
		   popupWindowFour.setAnimationStyle(R.style.mypopwindow_anim_style);
		   popupWindowFour.showAsDropDown(v);
		   listView__order.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				payType =arg2+"";
				mPay_type.setText(arraylist_order.get(arg2));
				popupWindowFour.dismiss();
			}
		});
		   
			PopuUtils.changeActivity(PaySelectActivity.this);
			PopuUtils.changeActivity(popupWindowFour,PaySelectActivity.this);
	}


     private void Pay(String paypassword,String type){
    	 
    	 HttpRequestUtils.doHttpPayJob(mJobID, type, paypassword, totalAmount, new MyAsyncHttpResponseHandler(getSupportFragmentManager(),getResources()) {
    		 @Override
    		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
    			// TODO Auto-generated method stub
    			super.onSuccess(arg0, arg1, arg2);
    			
    			try {
					JSONObject jsonO = new JSONObject(new String(arg2));
					
					if(jsonO.optBoolean("status")){//{"data":[{"amount":40,"code":"TW150707115249425","porductDesc":"李蕾公司[电话电话]","productName":"李蕾公司","tradeNo":"550150707115249567"}],"errMessage":"","status":true}
						
						JSONArray optJSONArray = jsonO.optJSONArray("data");
						
						if(optJSONArray.length()!=0){
							JSONObject optJSONObject = optJSONArray.optJSONObject(0);
							if("0".equals(payType)){
								PayAllUtuils.getStringAll(optJSONObject.optString("code"), "微兼职Android客户端", optJSONObject.optString("amount"),"付款", PaySelectActivity.this);
								
							}else{
								Misc.alert(optJSONObject.optString("message"));
								Intent intent = new Intent();  
								intent.setAction("com.guangzhi.weijianzhi");  
								sendBroadcast(intent);
							}
						}
					}
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    		}
    		 
    		 @Override
    		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
    				Throwable arg3) {
    			// TODO Auto-generated method stub
    			super.onFailure(arg0, arg1, arg2, arg3);
    		}
		});
    	 
     }
}
